package com.yoke.controller.sysadmin;

import com.yoke.common.JsonMessage;
import com.yoke.common.base.RewriteBaseControl;
import com.yoke.system.log.LogType;
import com.yoke.system.log.SystemLog;
import com.yoke.util.FileUtil;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/5/10.
 */
@Controller
@RequestMapping("sysadmin")
public class EditConfControl extends RewriteBaseControl {

    @RequestMapping(value = "edit_conf.html", produces = MediaType.TEXT_HTML_VALUE)
    public String edit_conf(String parent, String name) {
        parent = convertFilePath(parent);
        name = convertFilePath(name);
        String filePath = FileUtil.ClearPath(String.format("%s/%s/%s", getConfPath(), parent, name));
        try {
            String context = FileUtil.readToString(filePath);
            request.setAttribute("context", context);
            request.setAttribute("parent", parent);
            request.setAttribute("name", name);
            return "sysadmin/edit_conf";
        } catch (Exception e) {
            SystemLog.LOG(LogType.CONTROL_ERROR).error("异常", e);
            request.setAttribute("tip", "读取错误，请联系管理员");
        }
        return "sysadmin/edit_conf";
    }

    @RequestMapping(value = "save_conf.json", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public String edit_conf(String parent, String name, String context) {
        parent = convertFilePath(parent);
        name = convertFilePath(name);
        String filePath = FileUtil.ClearPath(String.format("%s/%s/%s", getConfPath(), parent, name));
        try {
            FileUtil.writeFile(filePath, context);
            reloadNginx("修改" + filePath);
            return JsonMessage.getString(200, "保存成功");
        } catch (IOException e) {
          SystemLog.ERROR().error("异常",e);
        }
        //System.out.println(context);
        return JsonMessage.getString(500, "保存失败");
    }

}
